package com.match.competition_apply.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.match.commonutils.Result;
import com.match.competition_apply.entity.CompetitionInfo;
import com.match.competition_apply.entity.CompetitionSignUp;
import com.match.competition_apply.entity.SignUpProgress;
import com.match.competition_apply.entity.vo.*;
import com.match.competition_apply.utils.CompetitionExcelByHutoolUtils;
import com.match.competition_apply.utils.SignUpWordUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author AdiosF
 * @since 2021-11-03
 */
@Api(tags = "报名模块")
@RestController
@RequestMapping("/competition_apply/competition-sign-up")
public class CompetitionSignUpController extends BaseController{
     @ApiOperation(value = "报名申请")
     @PostMapping("/addSignUpInfo")
     public Result addSignUpInfo(@RequestBody CompetitionSignUp competitionSignUp){
         CompetitionSignUp competitionSignUp1 = competitionSignUpService.saveSignInfo(competitionSignUp);
         String signUpId = competitionSignUp1.getId();
         //添加报名进度
         if (!StringUtils.isEmpty(competitionSignUp1)){
             SignUpProgress signUpProgress=new SignUpProgress();
             signUpProgress.setTitle("等待审核");
             signUpProgress.setDescription("请及时联系管理员审核");
             signUpProgress.setSignupId(signUpId);
             signUpProgress.setGmtCreate(competitionSignUp1.getGmtCreate());
             signUpProgress.setStates(0);
             signUpProgress.setType("primary");
             signUpProgress.setIcon("el-icon-more");
             signUpProgressService.save(signUpProgress);

             SignUpProgress signUpProgress1=new SignUpProgress();
             signUpProgress1.setTitle("完善申报书");
             signUpProgress1.setDescription("管理员审核通过后才能完善申报书");
             signUpProgress1.setSignupId(signUpId);
             signUpProgress1.setGmtCreate(null);
             signUpProgress1.setStates(3);
             signUpProgressService.save(signUpProgress1);


             SignUpProgress signUpProgress2=new SignUpProgress();
             signUpProgress2.setTitle("中期检查");
             signUpProgress2.setDescription("请提前准备所需材料");
             signUpProgress2.setSignupId(signUpId);
             signUpProgress2.setGmtCreate(null);
             signUpProgress2.setStates(4);
             signUpProgressService.save(signUpProgress2);
         }
         //分配队长
         String studentNumber = competitionSignUp.getStudentNumber();
         allotStudentRole(studentNumber,signUpId);
         return Result.ok().message("报名成功");
     }

     //分配学生角色
    public void allotStudentRole(String studentNumbers,String signUpId){
        if (!StringUtils.isEmpty(studentNumbers)){
            Map<String,Object> map=new HashMap<>();
            map.put("groupId",signUpId);
            String[] results=studentNumbers.split(",");
            String teamLeader=results[0];
            List<String> stringList=new ArrayList<>();
            //为此学生分配队长角色
            map.put("leaderId",teamLeader);
            //分配参赛学生
            for (int i = 1; i < results.length; i++) {
                stringList.add(results[i]);
            }
            map.put("studentId",stringList);
            courseClient.assignRoleToStudent(map);
        }
    }


    @ApiOperation("修改报名信息")
    @PostMapping("/updateSignUpInfo")
    public  Result updateSignUpInfo(@RequestBody CompetitionSignUp competitionSignUp){
         if (!StringUtils.isEmpty(competitionSignUp.getBackInfo())){
             competitionSignUp.setBackInfo("");
             //修改报名进度
             SignUpProgress signUpProgress=new SignUpProgress();
             signUpProgress.setTitle("等待审核");
             signUpProgress.setDescription("请及时联系管理员审核");
             signUpProgress.setSignupId(competitionSignUp.getId());
             signUpProgress.setGmtCreate(new Date());
             signUpProgress.setStates(0);
             signUpProgress.setType("primary");
             signUpProgress.setIcon("el-icon-more");
             signUpProgressService.update(signUpProgress,new QueryWrapper<SignUpProgress>().eq("signup_id",competitionSignUp.getId()).eq("states",2));
         }else {
             //修改报名进度的时间
             SignUpProgress signUpProgress=new SignUpProgress();
             signUpProgress.setGmtCreate(new Date());
             signUpProgressService.update(signUpProgress,new QueryWrapper<SignUpProgress>().eq("signup_id",competitionSignUp.getId()).eq("states",0));
         }
         competitionSignUp.setStates(0);
         competitionSignUpService.updateById(competitionSignUp);
         //删除中间表信息
         competitionSignUpService.removeStudentGrout(competitionSignUp.getId());
         //分配学生角色
         allotStudentRole(competitionSignUp.getStudentNumber(),competitionSignUp.getId());
         return Result.ok().message("报名信息修改成功");
    }

     @ApiOperation("分页条件查询报名信息")
     @PostMapping("/getSigbUpByQueryPage/{current}/{limit}")
     public Result getSigbUpByQueryPage(@ApiParam(required = true,value = "当前页")
                                        @PathVariable(value = "current")long current,
                                        @ApiParam(required = true,value = "每页记录数")
                                        @PathVariable(value = "limit")long limit,
                                        @RequestBody(required = false) SignUpQuery signUpQuery){
         Map<String,Object> map=competitionSignUpService.getSignUpPageList(current,limit,signUpQuery);
         long total = (long) map.get("total");
         List<CompetitionSignUp> records = (List<CompetitionSignUp>) map.get("records");
         if (total<=0){
             return Result.ok().data("records",null).data("total",0).message("暂无此纪录存在");
         }
         return Result.ok().data("total",total).data("records",records);
     }


     @ApiOperation("根据报名ID移除报名信息")
     @DeleteMapping("/deleteSignUpById/{signUpId}")
     public Result deleteSignUpById(@ApiParam(required = true,value = "报名ID")
                                    @PathVariable(value = "signUpId")String signUpId){
         //判断学生是否参加有其他比赛
         CompetitionSignUp competitionSignUp = competitionSignUpService.getById(signUpId);
         String studentNumber = competitionSignUp.getStudentNumber();
         if (!StringUtils.isEmpty(signUpId)){
             String[] split = studentNumber.split(",");
             for (String s : split) {
                 if (StringUtils.isEmpty(s)){
                     continue;
                 }
                 //更新学生参赛数
                 competitionSignUpService.upDateStudentCount(s);
             }
         }
         //移除中间表对应的角色信息
         competitionSignUpService.removeStudentGrout(signUpId);
         competitionSignUpService.removeById(signUpId);
         //根据报名ID移除报名进度信息
         signUpProgressService.remove(new QueryWrapper<SignUpProgress>().eq("signup_id",signUpId));
         return Result.ok().message("撤销成功");
     }



     @ApiOperation("获取指导老师")
     @GetMapping("/getAdviserTeacher")
     public Result getAdviserTeacher(){
         Object adviserOneList = courseClient.getAllTeacherUseAdviser().getData().get("adviserOneList");
         return Result.ok().data("adviserOneList",adviserOneList);
     }


     @ApiOperation("获得所有学生")
     @GetMapping("/getStudentTeam")
     public Result getStudentTeam(){
         Object allStudent = courseClient.getAllEntryStudent().getData().get("allStudent");
         return Result.ok().data("allStudentList",allStudent);
     }


     @ApiOperation("根据报名ID获取报名信息")
     @GetMapping("/getSignUpInfoById/{signUpId}")
     public Result getSignUpInfoById(@PathVariable(value = "signUpId")String signUpId){
         CompetitionSignUp competitionSignUpServiceById = competitionSignUpService.getById(signUpId);
         if (StringUtils.isEmpty(competitionSignUpServiceById)){
             return Result.error().message("查无此纪录");
         }
         //获取竞赛信息
         CompetitionInfo competitionInfo = competitionInfoService.getById(competitionSignUpServiceById.getGroupId());
         competitionInfo.setBegintime(CompetitionExcelByHutoolUtils.parseTimeToString(competitionInfo.getCompetitionBegin()));
         competitionInfo.setEndtime(CompetitionExcelByHutoolUtils.parseTimeToString(competitionInfo.getCompetitionEnd()));
         competitionSignUpServiceById.setCompetitionInfo(competitionInfo);
         //获取报名信息
         CompetitionSignUp competitionSignUp=competitionSignUpService.getSignUpInfo(competitionSignUpServiceById);
         return Result.ok().data("signUpInfo",competitionSignUp);
     }


     @ApiOperation("更新报名状态")
     @PostMapping("/updateSignUpStates")
     public Result updateSignUpStates(@RequestBody SignUpVo signUpVo){
         //更新状态1
         if (signUpVo.getStates().equals(1) && !StringUtils.isEmpty(signUpVo.getSignUpId())){
            SignUpProgress signUpProgress=new SignUpProgress();
            signUpProgress.setStates(1);
            signUpProgress.setTitle("已审核");
            signUpProgress.setDescription("管理员审核已通过");
            signUpProgress.setGmtModified(new Date());
            signUpProgress.setColor("#0bbd87");
            signUpProgress.setIcon("el-icon-check");
            signUpProgressService.update(signUpProgress,new QueryWrapper<SignUpProgress>().eq("signup_id",signUpVo.getSignUpId()).eq("states",0));


             SignUpProgress signUpProgress1=new SignUpProgress();
             signUpProgress1.setTitle("待完善申报书");
             signUpProgress1.setDescription("请您及时完善项目申报书的基本信息");
             signUpProgress1.setType("primary");
             signUpProgress1.setIcon("el-icon-more");
             signUpProgressService.update(signUpProgress1,new QueryWrapper<SignUpProgress>().eq("signup_id",signUpVo.getSignUpId()).eq("states",3));
         }
         //更新状态2
         if (signUpVo.getStates().equals(2) && !StringUtils.isEmpty(signUpVo.getSignUpId())){
             SignUpProgress signUpProgress=new SignUpProgress();
             signUpProgress.setStates(2);
             signUpProgress.setTitle("审核未通过");
             signUpProgress.setDescription("请您及时修改报名申请信息并再次提交报名申请");
             signUpProgress.setGmtModified(new Date());
             signUpProgress.setType("danger");
             signUpProgress.setColor(null);
             signUpProgress.setIcon("el-icon-circle-close");
             signUpProgressService.update(signUpProgress,new QueryWrapper<SignUpProgress>().eq("signup_id",signUpVo.getSignUpId()).eq("states",0));

         }
         //更新状态3
         if (signUpVo.getStates().equals(3) && !StringUtils.isEmpty(signUpVo.getSignUpId())){
             SignUpProgress signUpProgress=new SignUpProgress();
             signUpProgress.setTitle("已完善");
             signUpProgress.setDescription("您的申报书基本信息已完善");
             signUpProgress.setGmtModified(new Date());
             signUpProgress.setColor("#0bbd87");
             signUpProgress.setIcon("el-icon-document-checked");
             signUpProgressService.update(signUpProgress,new QueryWrapper<SignUpProgress>().eq("signup_id",signUpVo.getSignUpId()).eq("states",3));


             SignUpProgress signUpProgress1=new SignUpProgress();
             signUpProgress1.setTitle("等待中期检查");
             signUpProgress1.setDescription("请您及时与指导老师沟通提前准备所需材料");
             signUpProgress1.setType("primary");
             signUpProgress1.setIcon("el-icon-more");
             signUpProgressService.update(signUpProgress1,new QueryWrapper<SignUpProgress>().eq("signup_id",signUpVo.getSignUpId()).eq("states",4));


             SignUpProgress signUpProgress2=new SignUpProgress();
             signUpProgress2.setTitle("结题待变");
             signUpProgress2.setDescription("请您提前准备");
             signUpProgress2.setSignupId(signUpVo.getSignUpId());
             signUpProgress2.setStates(5);
             signUpProgressService.save(signUpProgress2);


             SignUpProgress signUpProgress3=new SignUpProgress();
             signUpProgress3.setTitle("项目评审");
             signUpProgress3.setDescription("评审结果");
             signUpProgress3.setSignupId(signUpVo.getSignUpId());
             signUpProgress3.setStates(6);
             signUpProgressService.save(signUpProgress3);
         }
         //更新状态4
         if (signUpVo.getStates().equals(4) && !StringUtils.isEmpty(signUpVo.getSignUpId())){
             SignUpProgress signUpProgress=new SignUpProgress();
             signUpProgress.setTitle("中期检查已完成");
             signUpProgress.setDescription("您的中期检查报告已在规定时间内完成");
             signUpProgress.setGmtModified(new Date());
             signUpProgress.setColor("#0bbd87");
             signUpProgress.setIcon("el-icon-s-promotion");
             signUpProgressService.update(signUpProgress,new QueryWrapper<SignUpProgress>().eq("signup_id",signUpVo.getSignUpId()).eq("states",4));


             SignUpProgress signUpProgress1=new SignUpProgress();
             signUpProgress1.setTitle("等待结题答辩");
             signUpProgress1.setDescription("请您提前准备结题所需材料");
             signUpProgress1.setType("primary");
             signUpProgress1.setIcon("el-icon-more");
             signUpProgressService.update(signUpProgress1,new QueryWrapper<SignUpProgress>().eq("signup_id",signUpVo.getSignUpId()).eq("states",5));
         }
         //更新状态5
         if (signUpVo.getStates().equals(5) && !StringUtils.isEmpty(signUpVo.getSignUpId())){
             SignUpProgress signUpProgress=new SignUpProgress();
             signUpProgress.setTitle("已完成");
             signUpProgress.setDescription("您的结题答辩已完成");
             signUpProgress.setGmtModified(new Date());
             signUpProgress.setColor("#0bbd87");
             signUpProgress.setIcon("el-icon-tickets");
             signUpProgressService.update(signUpProgress,new QueryWrapper<SignUpProgress>().eq("signup_id",signUpVo.getSignUpId()).eq("states",5));


             SignUpProgress signUpProgress1=new SignUpProgress();
             signUpProgress1.setTitle("待评审");
             signUpProgress1.setDescription("请您安心的等待评审结果");
             signUpProgress1.setType("primary");
             signUpProgress1.setIcon("el-icon-more");
             signUpProgressService.update(signUpProgress1,new QueryWrapper<SignUpProgress>().eq("signup_id",signUpVo.getSignUpId()).eq("states",6));


             SignUpProgress signUpProgress2=new SignUpProgress();
             signUpProgress2.setSignupId(signUpVo.getSignUpId());
             signUpProgress2.setTitle("学分替换");
             signUpProgress2.setStates(7);
             signUpProgress2.setDescription("您可以在评审结束以后选择要替换的课程");
             signUpProgressService.save(signUpProgress2);
         }
         //更新状态6
         if (signUpVo.getStates().equals(6) && !StringUtils.isEmpty(signUpVo.getSignUpId())){
             SignUpProgress signUpProgress=new SignUpProgress();
             signUpProgress.setTitle("已完成项目评审");
             signUpProgress.setDescription("请完成最终的学分置换");
             signUpProgress.setGmtModified(new Date());
             signUpProgress.setColor("#0bbd87");
             signUpProgress.setIcon("el-icon-s-claim");
             signUpProgressService.update(signUpProgress,new QueryWrapper<SignUpProgress>().eq("signup_id",signUpVo.getSignUpId()).eq("states",6));


             SignUpProgress signUpProgress1=new SignUpProgress();
             signUpProgress1.setTitle("待学分替换");
             signUpProgress1.setDescription("请您根据您的实际情况完成学分的替换");
             signUpProgress1.setType("primary");
             signUpProgress1.setIcon("el-icon-more");
             signUpProgressService.update(signUpProgress1,new QueryWrapper<SignUpProgress>().eq("signup_id",signUpVo.getSignUpId()).eq("states",7));

         }
         //更新状态7
         if (signUpVo.getStates().equals(7) && !StringUtils.isEmpty(signUpVo.getSignUpId())){
             SignUpProgress signUpProgress=new SignUpProgress();
             signUpProgress.setTitle("学分已置换");
             signUpProgress.setDescription("恭喜您已按时完成您的作品");
             signUpProgress.setGmtModified(new Date());
             signUpProgress.setColor("#0bbd87");
             signUpProgress.setIcon("el-icon-moon-night");
             signUpProgressService.update(signUpProgress,new QueryWrapper<SignUpProgress>().eq("signup_id",signUpVo.getSignUpId()).eq("states",7));
         }
         if (!StringUtils.isEmpty(signUpVo.getSignUpId()) && !StringUtils.isEmpty(signUpVo.getStates())){
             competitionSignUpService.updateSignUpStates(signUpVo.getSignUpId(),signUpVo.getStates(),signUpVo.getBackInfo());
             return Result.ok();
         }else {
             return Result.error().message("审理失败");
         }
     }


     @ApiOperation("获取驳回信息")
     @GetMapping("/getBackInfoById/{signUpId}")
     public Result getBackInfoById(@PathVariable(value = "signUpId")String signUpId){
         String backInfo=competitionSignUpService.getBackInfoById(signUpId);
         if (StringUtils.isEmpty(backInfo)){
             return Result.error().message("错误操作");
         }
         return Result.ok().data("backInfo",backInfo);
     }


     @ApiOperation("获取可置换的课程类别")
     @GetMapping("/getCourseType/{signUpId}")
     public Result getCourseType(@PathVariable(value = "signUpId")String signUpId){
         CompetitionSignUp competitionSignUpServiceById = competitionSignUpService.getOne(new QueryWrapper<CompetitionSignUp>().eq("id",signUpId).select("group_id"));
         CompetitionInfo competitionInfo = competitionInfoService.getOne(new QueryWrapper<CompetitionInfo>().eq("id", competitionSignUpServiceById.getGroupId()).select("replace_course"));
         String competitionType = competitionInfo.getReplaceCourse();
         String[] split = competitionType.split("/");
         List<Map<String, Object>> courseTypeList=new ArrayList<>();
         for (int i = 0; i < split.length; i++) {
             Map<String,Object> map=new HashMap<>();
             map.put("id",i);
             map.put("courseType",split[i]);
             courseTypeList.add(map);
         }
         return Result.ok().data("competitionTypeList",courseTypeList);
     }

     @ApiOperation("下载Word报名表")
     @PostMapping("/downLoadSignUpTable/{fileName}")
     public Result exportSignUpTable(HttpServletResponse response,
                                     @PathVariable(value = "fileName")String fileName,
                                     @RequestBody CompetitionSignUp competitionSignUp){
         //替换word文档中的内容，键值是word中的占位符value是要填充的值
         Map<String, Object> replaceMap = new HashMap<String, Object>();
//         replaceMap.put("name",competitionSignUp.getLeaderName());
//         replaceMap.put("number",competitionSignUp.getLeaderNumber());
//         replaceMap.put("major",competitionSignUp.getMajor());
//         replaceMap.put("grade",competitionSignUp.getGrade());
         replaceMap.put("workName",competitionSignUp.getWorkName());
         replaceMap.put("competitionType",competitionSignUp.getCompetitionInfo().getCompetitionType());
//         replaceMap.put("oneTeacherName",competitionSignUp.getOneTeacherName());
//         replaceMap.put("twoTeacherName",competitionSignUp.getTwoTeacherName());
         replaceMap.put("competitionDepartment",competitionSignUp.getCompetitionInfo().getCompetitionDepartment());

         SignUpWordUtil.toWord(fileName, response, replaceMap);
         return Result.ok();
     }

    @ApiOperation("下载Word申请书")
    @PostMapping("/downLoadSignUpTableById")
    public Result downLoadSignUpTableById(HttpServletResponse response,
                                    @RequestBody FileVo fileVo){
        CompetitionSignUp competitionSignUpServiceById = competitionSignUpService.getById(fileVo.getId());
        CompetitionInfo competitionInfo = competitionInfoService.getOne(new QueryWrapper<CompetitionInfo>().eq("id", competitionSignUpServiceById.getGroupId()));
        System.out.println("competitionSignUpServiceById = " + competitionSignUpServiceById);
        System.out.println("competitionInfo = " + competitionInfo);
        //替换word文档中的内容，键值是word中的占位符value是要填充的值
        Map<String, Object> replaceMap = new HashMap<String, Object>();
//         replaceMap.put("name",competitionSignUp.getLeaderName());
//         replaceMap.put("number",competitionSignUp.getLeaderNumber());
//         replaceMap.put("major",competitionSignUp.getMajor());
//         replaceMap.put("grade",competitionSignUp.getGrade());
        replaceMap.put("workName",competitionSignUpServiceById.getWorkName());
        replaceMap.put("competitionType",competitionInfo.getCompetitionType());
//         replaceMap.put("oneTeacherName",competitionSignUp.getOneTeacherName());
//         replaceMap.put("twoTeacherName",competitionSignUp.getTwoTeacherName());
        replaceMap.put("competitionDepartment",competitionInfo.getCompetitionDepartment());
        System.out.println("replaceMap = " + replaceMap);
        SignUpWordUtil.toWord(fileVo.getTablesName(), response, replaceMap);
        return Result.ok();
    }

    @ApiOperation("报名的学分认证")
    @PostMapping("/affirmCredit")
    public Result affirmCredit(@RequestBody AffirmCreditVo affirmCreditVo){
        if (!StringUtils.isEmpty(affirmCreditVo.getSignupInfoId())){
            CompetitionSignUp competitionSignUp = competitionSignUpService.getById(affirmCreditVo.getSignupInfoId());
            if (!StringUtils.isEmpty(affirmCreditVo.getAcquisitionLever())){
                competitionSignUp.setAcquisitionLever(affirmCreditVo.getAcquisitionLever());
            }
            if (!StringUtils.isEmpty(affirmCreditVo.getAffirmCredit())){
                competitionSignUp.setAffirmCredit(affirmCreditVo.getAffirmCredit());
                //将认证学分加入学生的记录当中
                courseClient.updateStudentCredit(affirmCreditVo.getSignupInfoId(),affirmCreditVo.getAffirmCredit());
            }
            if (!StringUtils.isEmpty(affirmCreditVo.getAffirmGrade())){
                competitionSignUp.setAffirmGrade(affirmCreditVo.getAffirmGrade());
            }
            competitionSignUp.setWinprize(affirmCreditVo.getWinPrize());
            //获取当前时间
            Date d = new Date();
//        SimpleDateFormat sdf = new SimpleDateFormat("yyMMddE HH:mm:ss");
//        String format = sdf.format(d);
            competitionSignUp.setCarryTime(d);
            competitionSignUpService.updateById(competitionSignUp);
            return Result.ok();
        }else {
            return Result.error().message("网络延迟请稍后认证");
        }
    }


    @ApiOperation("学生-分页查询自己已报名的项目")
    @PostMapping("/studentGetSignUp/{current}/{limit}")
    public Result studentGetSignUp(@ApiParam(required = true,value = "当前页")
                                   @PathVariable(value = "current")long current,
                                   @ApiParam(required = true,value = "每页记录数")
                                   @PathVariable(value = "limit")long limit,
                                   @RequestBody(required = false) StudentSignUpVo studentSignUpVo){
        Map<String,Object> map=competitionSignUpService.getStudentSignUpList(current,limit,studentSignUpVo);
        long total = (long) map.get("total");
        List<CompetitionSignUp> records = (List<CompetitionSignUp>) map.get("records");
        if (total<=0){
            return Result.ok().data("records",null).data("total",0).message("暂无此纪录存在");
        }
        return Result.ok().data("total",total).data("records",records);
    }
 }

